package com.paradogs.framework.core.msg;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.*;

/**
 * @author: yumi
 * @date: 2023/8/13  13:56
 * @Description: 消息上下文
 */
@Data
public class PRMsgContextHolder {

    /**
     * 上下文信息
     */
    private static ThreadLocal<Snapshot> context = new ThreadLocal<>();

    public static void releaseContext() {
        context.remove();
    }


    public static void setContext(ChannelHandlerContext ctx, Long playerId, MsgHeader header) {
        Snapshot snapshot = new Snapshot(ctx, playerId, header);
        context.set(snapshot);
    }

    public static void setContext(Snapshot snapshot) {
        context.set(snapshot);
    }


    /**
     * 返回当前上下文快照
     */
    public static PRMsgContextHolder.Snapshot getSnapshot() {
        return context.get();
    }

    public static Channel getChannel() {
        return getCtx().channel();
    }

    public static ChannelHandlerContext getCtx() {
        Snapshot snapshot = getSnapshot();
        if (snapshot == null) {
            return null;
        }
        return snapshot.getCtx();
    }

    public static Long getPlayerId() {
        Snapshot snapshot = getSnapshot();
        if (snapshot == null) {
            return null;
        }
        return snapshot.getPlayId();
    }

    public static MsgHeader getMsgHeader() {
        Snapshot snapshot = getSnapshot();
        if (snapshot == null) {
            return null;
        }
        return snapshot.getHeader();
    }

    /**
     * 快照，与 MsgContextHolder 属性相同
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Snapshot {
        private ChannelHandlerContext ctx;
        private Long playId;
        private MsgHeader header;
    }

}
